<template>
  <el-dialog
    :title="isBatch ? '批量添加人员' : '添加人员'"
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    width="600px"
    destroy-on-close
    :close-on-click-modal="false"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <el-form-item label="人员" :prop="isBatch ? 'personnelIds' : 'personnelId'">
        <template v-if="isBatch">
          <el-select
            v-model="formData.personnelIds"
            multiple
            filterable
            remote
            :remote-method="remoteSearch"
            :loading="loading"
            placeholder="请选择人员"
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="item in personnelOptions"
              :key="item.personnelId"
              :label="`${item.personnelCode} - ${item.personnelName}`"
              :value="item.personnelId"
            >
              <div class="personnel-option">
                <div>{{ item.personnelCode }} - {{ item.personnelName }}</div>
                <div class="personnel-option-info">
                  {{ item.supplierName }} | {{ item.levelName || getLevelName(item.level) }} |
                  {{ item.monthlyRate }}元/月
                </div>
              </div>
            </el-option>
          </el-select>
        </template>
        <template v-else>
          <el-select
            v-model="formData.personnelId"
            filterable
            remote
            :remote-method="remoteSearch"
            :loading="loading"
            placeholder="请选择人员"
            style="width: 100%"
            @change="handlePersonnelChange"
            clearable
          >
            <el-option
              v-for="item in personnelOptions"
              :key="item.personnelId"
              :label="`${item.personnelCode} - ${item.personnelName}`"
              :value="item.personnelId"
            >
              <div class="personnel-option">
                <div>{{ item.personnelCode }} - {{ item.personnelName }}</div>
                <div class="personnel-option-info">
                  {{ item.supplierName }} | {{ item.levelName || getLevelName(item.level) }} |
                  {{ item.monthlyRate }}元/月
                </div>
              </div>
            </el-option>
          </el-select>
        </template>
      </el-form-item>

      <el-form-item label="开始日期" prop="startDate">
        <el-date-picker
          v-model="formData.startDate"
          type="date"
          placeholder="选择开始日期"
          style="width: 100%"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <el-form-item label="结束日期" prop="endDate">
        <el-date-picker
          v-model="formData.endDate"
          type="date"
          placeholder="选择结束日期"
          style="width: 100%"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <el-form-item label="人月单价" prop="monthlyRate" v-if="!isBatch">
        <el-input-number
          v-model="formData.monthlyRate"
          :precision="2"
          :min="0"
          :max="100000"
          :step="1000"
          style="width: 100%"
          placeholder="请输入人月单价（元/月）"
        />
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" type="textarea" rows="3" placeholder="请输入备注信息" />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="$emit('update:visible', false)">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent, ref, watch, reactive, nextTick, onMounted } from "vue";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import {
  getAvailablePersonnelList,
  addOrderPersonnel,
  batchAddOrderPersonnel
} from "@/api/attendance/orderPersonnel";
import type {
  AddOrderPersonnelRequest,
  BatchAddOrderPersonnelRequest
} from "@/types/attendance/order/personnelRelation";

interface PersonnelOption {
  personnelId: number;
  personnelCode: string;
  personnelName: string;
  supplierId?: number;
  supplierName?: string;
  level?: string;
  levelName?: string;
  monthlyRate: number;
}

export default defineComponent({
  name: "AddPersonnelDialog",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    isBatch: {
      type: Boolean,
      default: false
    },
    orderId: {
      type: Number,
      required: true
    }
  },
  emits: ["update:visible", "success"],
  setup(props, { emit }) {
    // 表单引用
    const formRef = ref<FormInstance>();
    const loading = ref(false);
    const submitting = ref(false);
    const personnelOptions = ref<PersonnelOption[]>([]);

    // 表单数据
    const formData = reactive({
      orderId: props.orderId,
      personnelId: null as number | null,
      personnelIds: [] as number[],
      startDate: "",
      endDate: "",
      monthlyRate: 0,
      remark: ""
    });

    // 表单验证规则
    const rules = reactive<FormRules>({
      personnelId: [{ required: true, message: "请选择人员", trigger: "change" }],
      personnelIds: [
        {
          required: true,
          validator: (_rule, value, callback) => {
            if (!value || value.length === 0) {
              callback(new Error("请选择至少一名人员"));
            } else {
              callback();
            }
          },
          trigger: "change"
        }
      ],
      startDate: [{ required: true, message: "请选择开始日期", trigger: "change" }],
      monthlyRate: [
        { required: !props.isBatch, message: "请输入人月单价", trigger: "blur" },
        { type: "number", min: 0, message: "人月单价必须大于0", trigger: "blur" }
      ]
    });

    // 加载人员列表
    async function loadPersonnelList(query = "") {
      if (!props.orderId) return;

      loading.value = true;
      try {
        const { data } = await getAvailablePersonnelList(props.orderId, {
          pageNum: 1,
          pageSize: 20,
          personnelName: query || undefined,
          personnelCode: query || undefined
        });

        personnelOptions.value = data.rows;
      } catch (error) {
        console.error("获取人员列表失败:", error);
      } finally {
        loading.value = false;
      }
    }

    // 远程搜索人员
    async function remoteSearch(query: string) {
      await loadPersonnelList(query);
    }

    // 获取级别名称
    function getLevelName(level?: string): string {
      if (!level) return "";

      const levelMap: Record<string, string> = {
        "01": "初级",
        "02": "中级",
        "03": "高级",
        "04": "专家",
        "1": "初级",
        "2": "中级",
        "3": "高级",
        "4": "专家"
      };

      return levelMap[level] || "";
    }

    // 监听人员变化
    function handlePersonnelChange(personnelId: number) {
      if (!personnelId) return;

      const selected = personnelOptions.value.find(item => item.personnelId === personnelId);
      if (selected) {
        formData.monthlyRate = selected.monthlyRate;
      }
    }

    // 提交表单
    async function handleSubmit() {
      if (!formRef.value) return;

      await formRef.value.validate(async valid => {
        if (!valid) return;

        submitting.value = true;
        try {
          let success = false;

          if (props.isBatch) {
            // 提交批量添加请求
            const batchData: BatchAddOrderPersonnelRequest = {
              orderId: props.orderId,
              personnelIds: formData.personnelIds,
              startDate: formData.startDate,
              endDate: formData.endDate || undefined,
              monthlyRate: formData.monthlyRate,
              remark: formData.remark || undefined
            };

            const { code, msg } = await batchAddOrderPersonnel(batchData);
            success = code === 0;
            if (!success) {
              ElMessage.error(msg || "批量添加人员失败");
            }
          } else {
            // 提交单个添加请求
            if (!formData.personnelId) {
              ElMessage.error("请选择人员");
              submitting.value = false;
              return;
            }

            const singleData: AddOrderPersonnelRequest = {
              orderId: props.orderId,
              personnelId: formData.personnelId,
              startDate: formData.startDate,
              endDate: formData.endDate || undefined,
              monthlyRate: formData.monthlyRate,
              remark: formData.remark || undefined
            };

            const { code, msg } = await addOrderPersonnel(singleData);
            success = code === 0;
            if (!success) {
              ElMessage.error(msg || "添加人员失败");
            }
          }

          if (success) {
            ElMessage.success("添加成功");
            emit("update:visible", false);
            emit("success");
          }
        } catch (error) {
          console.error("提交失败:", error);
          ElMessage.error("操作失败，请重试");
        } finally {
          submitting.value = false;
        }
      });
    }

    // 重置表单
    function resetForm() {
      if (formRef.value) {
        formRef.value.resetFields();
      }
      formData.personnelId = null;
      formData.personnelIds = [];
      formData.startDate = "";
      formData.endDate = "";
      formData.monthlyRate = 0;
      formData.remark = "";
      personnelOptions.value = [];
    }

    // 监听对话框显示状态变化
    watch(
      () => props.visible,
      val => {
        if (!val) {
          nextTick(() => {
            resetForm();
          });
        } else {
          formData.orderId = props.orderId;
          // 加载人员列表
          loadPersonnelList();
        }
      }
    );

    // 监听orderId变化
    watch(
      () => props.orderId,
      val => {
        formData.orderId = val;
        if (props.visible) {
          loadPersonnelList();
        }
      }
    );

    // 组件挂载时，如果对话框可见则加载人员列表
    onMounted(() => {
      if (props.visible && props.orderId) {
        loadPersonnelList();
      }
    });

    return {
      formRef,
      formData,
      rules,
      loading,
      submitting,
      personnelOptions,
      handleSubmit,
      remoteSearch,
      handlePersonnelChange,
      getLevelName
    };
  }
});
</script>

<style scoped>
.personnel-option {
  display: flex;
  flex-direction: column;
}

.personnel-option-info {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.dialog-footer {
  margin-top: 20px;
  text-align: right;
}
</style>
